#include "Online.h"
#include "ui_Online.h"
#include "TcpClient.h"

Online::Online(QWidget* parent) :
	QWidget(parent),
	ui(new Ui::Online)
{
	ui->setupUi(this);
}

Online::~Online()
{
	delete ui;
}

//根据PDU中的caMsg 显示出其包含的所有用户名在【在线用户】栏
void Online::showUsr(PDU* pdu)
{
	if (pdu == NULL) {
		return;
	}
	QListWidgetItem* pItemTemp = NULL;
	int row = ui->online_lw->count();
	while (ui->online_lw->count() > 0) {
		pItemTemp = ui->online_lw->item(row - 1);
		ui->online_lw->removeItemWidget(pItemTemp);
		delete(pItemTemp);
		row--;
	}
	uint uiSize = pdu->uiMsgLen / 32;
	char caTmp[32] = { '\0' };
	char caUsrName[32] = { '\0' };
	memcpy(caUsrName, TcpClient::getInstance().getStrName().toLocal8Bit().data(), 32);
	for (uint i = 0; i < uiSize; i++) {
		memcpy(caTmp, (char*)pdu->caMsg + i * 32, 32);
		if (strcmp(caTmp, caUsrName) == 0) {	//删去自己的名字
			continue;
		}
		ui->online_lw->addItem(caTmp);
	}
}

//点击添加好友后运行
void Online::on_addFriend_pb_clicked() {
	qDebug() << "addFriend执行一次";
	QListWidgetItem* pItem = ui->online_lw->currentItem();
	PDU* pdu = mkPDU(0);
	//pdu->caData存放name；pdu->caData+32存放perName
	strcpy(pdu->caData, TcpClient::getInstance().getStrName().toLocal8Bit().data());
	strcpy(pdu->caData + 32, pItem->text().toLocal8Bit().data());
	pdu->uiMsgType = ENUM_MESSAGE_TYPE_ADD_FRIEND_REQUEST;
	TcpClient::getInstance().getTcpSocket().write((char*)pdu, pdu->uiPDULen);
	free(pdu);
	pdu = NULL;
}
